<template>
  <div class="container mx-auto px-4 py-6">
    <div style="display: grid; justify-content: center; align-items: center;">
      <h1 class="text-2xl font-bold text-gray-800 mb-6">部门管理</h1>
    </div>
    <div class="action-bar bg-white rounded-lg shadow-md p-4 mb-6 flex flex-col md:flex-row md:items-center gap-4">
      <div class="search-container flex-1 flex">
        <input
            type="text"
            v-model="searchQuery"
            placeholder="搜索部门名称..."
            class="flex-1 px-4 py-2 border border-gray-300 rounded-l-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
        >
        <button
            @click="selectDepartments"
            class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-r-md transition-colors"
        >
          <i class="fa fa-search mr-2">搜索</i>
        </button>
      </div>

      <button @click="openAddModal" class="bg-green-500 hover:bg-green-600 text-white px-4 py-2 rounded-md transition-colors flex items-center">
        <i class="fa fa-plus mr-2">新增部门</i>
      </button>
    </div>

    <!-- 部门表格 -->
    <div class="table-container w-full bg-white rounded-lg shadow-md overflow-hidden">
      <table class="department-table w-full">
        <thead>
        <tr class="bg-gray-50">
          <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
          <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">部门名称</th>
          <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">人数</th>
          <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">创建时间</th>
          <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">修改时间</th>
          <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
        </tr>
        </thead>
        <tbody class="divide-y divide-gray-200">
        <tr v-for="dept in departments" :key="dept.id" class="hover-row hover:bg-gray-50 transition-colors">
          <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ dept.id }}</td>
          <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ dept.name }}</td>
          <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ dept.employeeCount }}</td>
          <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ dept.createTime}}</td>
          <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ dept.updateTime}}</td>
          <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
            <button
                @click="deleteDepartment(dept.id)"
                class="text-red-500 hover:text-red-700 transition-colors"
            >
              <i class="fa fa-trash mr-1">删除</i>
            </button>
          </td>
        </tr>
        </tbody>
      </table>
    </div>

    <!-- 空状态提示 -->
    <div v-if="departments.length === 0" class="empty-state w-full bg-white rounded-lg shadow-md p-8 text-center">
      <div class="empty-icon text-6xl text-gray-400 mb-4">
        <i class="fa fa-folder-open-o"></i>
      </div>
      <p class="text-gray-600 mb-4">暂无部门数据</p>
    </div>

    <!-- 新增部门模态框 -->
    <div v-if="showAddModal" class="modal-overlay fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div class="modal-content bg-white rounded-lg shadow-xl w-full max-w-md transform transition-all">
        <div class="modal-header flex justify-between items-center border-b">
          <h3 class="text-lg font-medium text-gray-900 flex">新增部门</h3>
          <button @click="showAddModal = false" class="text-gray-400 hover:text-gray-600">
            <i class="fa fa-times"></i>
          </button>
        </div>

        <div class="modal-body p-4">
          <div class="form-group mb-4">
            <label for="deptName" class="block text-sm font-medium text-gray-700 mb-1">部门名称</label>
            <input
                type="text"
                id="deptName"
                v-model="newDeptName"
                class="form-control w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                placeholder="请输入部门名称"
            >
            <p v-if="nameExists" class="mt-1 text-red-500 text-sm">该部门名称已存在</p>
            <label for="deptName" class="block text-sm font-medium text-gray-700 mb-1">创建时间</label>
            <input
                type="date"
                v-model="departmentsCreateTime"
                min="1900"
                max="2099"
                class="form-control w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                :disabled="showViewModal"
            >
            <label for="deptName" class="block text-sm font-medium text-gray-700 mb-1">修改时间</label>
            <input
                type="date"
                v-model="departmentsUpdateTime"
                class="form-control w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                :disabled="showViewModal"
            >
          </div>
        </div>
        <div class="modal-footer flex justify-end p-4 border-t border-gray-200">
          <button @click="showAddModal = false" class="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50 transition-colors">
            取消
          </button>
          <button
              @click="addDepartment"
              :disabled="!newDeptName.trim() || nameExists"
              class="px-4 py-2 bg-blue-500 hover:bg-blue-600 text-white rounded-md transition-colors"
          >
            保存
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import axios from 'axios'
// 状态管理
const departments = ref([])
const searchQuery = ref('')
const showAddModal = ref(false)
const newDeptName = ref('')
const showViewModal = ref(true)
const employeeCount = ref(0)
const nameExists = ref(false)
const isLoading = ref(false)
const departmentsCreateTime = ref( '')
const departmentsUpdateTime = ref('')

// 生命周期钩子：页面加载时获取部门数据
onMounted(() => {
  fetchDepartments()
})

// 获取部门数据
const fetchDepartments = async () => {
  isLoading.value = true
  try {
    let url = '/api/dept'
    const response = await fetch(url)
    const data = await response.json()

    if (response.ok && data.code === 200) {
      departments.value = data.data || []
    } else {
      throw new Error(data.msg || '请求失败')
    }
  } catch (error) {
    alert(`获取部门数据失败：${error.message}`)
    console.error('获取部门数据失败:', error)
  } finally {
    isLoading.value = false
  }
}

// 检查部门名称是否已存在
const checkNameExists = () => {
  if (!newDeptName.value.trim()) {
    nameExists.value = false
    return
  }

  nameExists.value = departments.value.some(
      dept => dept.name.toLowerCase() === newDeptName.value.toLowerCase().trim()
  )
}

// 监听输入变化，实时检查名称是否存在
watch(newDeptName, checkNameExists)

// 打开新增模态框
const openAddModal = () => {
  newDeptName.value = ''
  employeeCount.value = 0
  nameExists.value = false
  showAddModal.value = true
  showViewModal.value = false
}

// 新增部门
const addDepartment = async () => {
  if (!newDeptName.value.trim()) {
    alert('请输入部门名称')
    return
  }

  if (nameExists.value) {
    alert('该部门名称已存在')
    return
  }

  try {
    const response = await fetch('/api/dept', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        name: newDeptName.value,
        createTime: departmentsCreateTime.value || 0,
        updateTime: departmentsUpdateTime.value || 0
      })
    })
    const data = await response.json()

    if (response.ok && data.code === 200) {
      alert('部门添加成功')
      showAddModal.value = false
      fetchDepartments() // 重新获取数据
    } else {
      throw new Error(data.msg || '添加失败')
    }
  } catch (error) {
    alert(`部门添加失败：${error.message}`)
    console.error('部门添加失败:', error)
  }
}

// 删除部门
const deleteDepartment = async (id) => {
  if (!confirm('确定要删除这个部门吗？删除后相关数据可能会受到影响。')) {
    return
  }

  try {
    const response = await fetch(`/api/dept/${id}`, { method: 'DELETE' })
    const data = await response.json()

    if (response.ok && data.code === 200) {
      alert('部门删除成功')
      fetchDepartments() // 重新获取数据
    } else {
      throw new Error(data.msg || '删除失败')
    }
  } catch (error) {
    alert(`部门删除失败：${error.message}`)
    console.error('部门删除失败:', error)
  }
}

const selectDepartments = async () => {

    isLoading.value = true
    try {
      const response = await axios.get(`/api/dept/${searchQuery.value}`, { method: 'GET' })
      const data = await response.data
      if (data.code === 200) {
        departments.value = data.data || []
      } else {
        throw new Error(data.msg || '请求失败')
      }
    } catch (error) {
      alert(`获取部门数据失败：${error.message}`)
      console.error('获取部门数据失败:', error)
    } finally {
      isLoading.value = false
    }
}

</script>

<style scoped>
/* 导入Font Awesome */
@import url('https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css');

/* 基础样式 */
.container {
  margin: 0 auto;
}

h1 {
  font-size: 24px;
  color: #333;
}

/* 操作栏样式 */
.action-bar {
  display: flex;
  gap: 1rem;
}

.search-container {
  display: flex;
  flex: 1;
}

/* 表格样式 */
.table-container {
  width: 100%;
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);
}

.department-table {
  width: 100%;
  border-collapse: collapse;
}

.department-table th, .department-table td {
  padding: 12px 15px;
  text-align: left;
  border-bottom: 1px solid #e0e0e0;
}

.department-table th {
  background-color: #f5f5f5;
  font-weight: 600;
  color: #333;
}

.department-table tr:last-child td {
  border-bottom: none;
}

.hover-row:hover {
  background-color: #f5f5f5;
}

/* 空状态样式 */
.empty-state {
  text-align: center;
  padding: 40px;
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);
}

.empty-icon {
  font-size: 60px;
  color: #aaa;
  margin-bottom: 20px;
}

.empty-state p {
  font-size: 16px;
  color: #666;
  margin-bottom: 20px;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0,0,0,0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-content {
  background-color: white;
  border-radius: 4px;
  width: 90%;
  max-width: 400px;
  box-shadow: 0 5px 15px rgba(0,0,0,0.3);
}

.modal-header {
  padding: 15px 20px;
  border-bottom: 1px solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}


.modal-body {
  padding: 20px;
}

.modal-footer {
  padding: 15px 20px;
  border-top: 1px solid #e0e0e0;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 表单样式 */
.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-size: 14px;
  color: #333;
}

.form-control {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.form-control:focus {
  outline: none;
  border-color: #4285f4;
  box-shadow: 0 0 0 2px rgba(66, 133, 244, 0.2);
}



/* 按钮样式 */
button {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>